package com.zzyl.common;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.utils.bean.BeanUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

public class CopyTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher teacher = new Teacher("一个美男子");
        Student  student = new Student("小王", 18, teacher);
        // 浅拷贝
        // Student cloned = (Student) student.clone();
        // Student cloned = new Student();
        // BeanUtils.copyProperties(student, cloned);
        // Student cloned = BeanUtil.toBean(student, Student.class);
        // 深拷贝
        String s = JSON.toJSONString(student);
        Student cloned = JSON.parseObject(s, Student.class);

        // 修改原对象的引用类型字段
        student.getTeacher().setTeacherName("一个美女") ;

        System.out.println("student原对象: " + student);    //   Teacher的名字变了
        System.out.println("student克隆后的对象: " + cloned);     // Teacher的名字也变了（浅拷贝共享引用） 如果没有变就是深克隆
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student implements Cloneable {
    private String name;
    private int age;
    private Teacher teacher; // 引用类型
    // 重写 clone() 方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 默认是浅拷贝
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + ", teacher=" + teacher + "}";
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Teacher {
    private String teacherName;
    @Override
    public String toString() {
        return "Teacher{teacherName='" + teacherName + "'}";
    }
}
